package com.capsulode.excel.util;


import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

public class ExcelUtil {
    public static final String MIME_XLS="application/vnd.ms-excel";
    public static final String MIME_XLSX="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

    public static Collection<String> raw(Row row) {
        return StreamSupport.stream(row.spliterator(), false)
                .map(Cell::toString)
                .collect(Collectors.toList());
    }

    public static Workbook guessInstanceFromContentTypeOrFilename(InputStream is, String contentTypeOrFilename) throws IOException {
        switch (contentTypeOrFilename) {
            case MIME_XLS:
                return new HSSFWorkbook(is);
            case MIME_XLSX:
                return new XSSFWorkbook(is);
            default:
                int lastDot = contentTypeOrFilename.lastIndexOf('.');
                if (lastDot >= 0) {
                    String ext = contentTypeOrFilename.substring(lastDot);
                    if (".xlsx".equalsIgnoreCase(ext)) {
                        return new XSSFWorkbook(is);
                    }
                }
                return new HSSFWorkbook(is);
        }
    }
}
